package org.jeeasy.sso.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.jeeasy.common.core.config.constant.CommonConstant;
import org.jeeasy.common.core.domain.IAuthUser;
import org.jeeasy.common.core.enums.RestCode;
import org.jeeasy.common.core.exception.JeeasyException;
import org.jeeasy.common.core.service.CurrentAuthUserService;
import org.jeeasy.common.core.tools.Tools;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author AlpsDDJ
 * @date 2020/11/24 9:16
 */
@Slf4j
@Service
public class CurrentAuthUserServiceImpl implements CurrentAuthUserService {
    @Override
    public IAuthUser getCurrentAuthUser() {
        return StpUtil.getSession().getModel(IAuthUser.SESSION_KEY, IAuthUser.class);
    }

    @Override
    public IAuthUser getCurrentAuthUser(ServletRequest request) {
        //StpUtil.checkLogin();
        HttpServletRequest httpServerRequest = (HttpServletRequest) request;

        AtomicReference<String> token = new AtomicReference<>(httpServerRequest.getHeader(CommonConstant.X_ACCESS_TOKEN));
        if (StrUtil.isBlank(token.get())) {
            Arrays.stream(httpServerRequest.getCookies()).forEach(httpCookie -> {
                String name = httpCookie.getName();
                if (CommonConstant.X_ACCESS_TOKEN.equals(name)) {
                    token.set(httpCookie.getValue());
                }
            });
        }
        if (Tools.isEmpty(token.get())) {
            throw new JeeasyException(RestCode.NO_USER);
        }
        Object loginIdByToken = StpUtil.getLoginIdByToken(token.get());
        if (Tools.isEmpty(loginIdByToken)) {
            throw new JeeasyException(RestCode.NO_USER);
        }
        SaSession saSession = StpUtil.getSessionByLoginId(loginIdByToken);
        return saSession.getModel(IAuthUser.SESSION_KEY, IAuthUser.class);
    }
}
